using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ERP.Api.Models;
using ERP.Infeartructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using REP.Domain.Entities;
using AgriSmart.ErrorCode;

namespace ERP.Api.Controllers
{
    /// <summary>
    /// 认证控制器（开发环境简单登录，不使用JWT）。
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly ErpDbContext _db;
        private static readonly Dictionary<string, string> _tokenStore = new(); // 简易 token 存储

        public AuthController(ErpDbContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 简单登录（用户名/密码），返回开发用简易 Token。
        /// </summary>
        /// <param name="req">登录请求</param>
        /// <returns>登录响应</returns>
        [HttpPost("Login")]
        public async Task<ActionResult<ApiResult<LoginResponseDto>>> Login([FromBody] LoginRequestDto req)
        {
            if (string.IsNullOrWhiteSpace(req.UserName) || string.IsNullOrWhiteSpace(req.Password))
            {
                return new ApiResult<LoginResponseDto>
                {
                    Code = ERP.ErrorCode.BaseEnums.BadRequest,
                    Msg = "用户名或密码不能为空",
                    Data = null!
                };
            }

            var user = await _db.Users!.AsNoTracking()
                .FirstOrDefaultAsync(x => x.Enabled == true && x.UserName == req.UserName && x.Password == req.Password);

            if (user == null)
            {
                return new ApiResult<LoginResponseDto>
                {
                    Code = ERP.ErrorCode.BaseEnums.Unauthorized,
                    Msg = "用户名或密码错误",
                    Data = null!
                };
            }

            // 生成一个简单 token（非JWT，仅开发用）
            var token = Guid.NewGuid().ToString("N");
            _tokenStore[token] = user.Id?.ToString() ?? string.Empty;

            var dto = new LoginResponseDto
            {
                Token = token,
                UserId = user.Id?.ToString(),
                UserName = user.UserName,
                RealName = user.RealName
            };

            return new ApiResult<LoginResponseDto>
            {
                Code = ERP.ErrorCode.BaseEnums.Success,
                Msg = "ok",
                Data = dto
            };
        }
    }
}
